<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="hAdd">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template slot-scope="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="200" label="启用">
          <template slot-scope="{row}">

            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>
              {{ row.state === 1 ? '已启用' : '未启用' }}
            </span>

          </template>
        </el-table-column>

        <el-table-column align="center" label="描述">
          <template slot-scope="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="200"
        >
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="text" size="small" @click="hOk(row)">确认</el-button>
              <el-button type="text" size="small" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配权限</el-button>
              <el-button type="text" size="small" @click="hEdit(row)">编辑</el-button>
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                @onConfirm="hDel(row.id)"
              >
                <el-button slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件
        total: 总数据条数
        page-size: 每页几条数据
        @current-change： 页码变化（用户点击）执行，自动传入当前的页码
        -->
        <el-pagination
          :current-page="page"
          :page-sizes="[3,5,7]"
          :background="true"
          layout="prev, pager, next, sizes"
          :total="total"
          :page-size="pagesize"
          @current-change="hCurrentChage"
          @size-change="hSizeChange"
        />
      </el-row>
    </div>

    <el-dialog :visible.sync="showDialog">
      <el-form ref="roleForm" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="formData.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="formData.description" type="textarea" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="mini" @click="hSave">确定</el-button>
          <el-button size="mini">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <assignPermission ref="refPerm" :show-dialog-perm.sync="showDialogPerm" :role-id="roleId" />
  </div>
</template>
<script>
import { getRoles, addRole, updateRole, delRole } from '@/api/role.js'
import assignPermission from './components/assignPermission.vue'
export default {
  name: 'Role',
  components: { assignPermission },
  data() {
    return {
      roleId: -1,
      showDialogPerm: false,
      formData: {
        name: '测试',
        state: 1,
        description: '描述信息'
      },
      showDialog: false, // 添加角色弹层

      list: [],
      total: 0,
      pagesize: 5,
      page: 1
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async hDel(id) {
      console.log(id)
      await delRole(id)
      this.$message.success('删除成功')
      if (this.list.length === 1) {
        if (this.page > 1) {
          this.page--
        }
      }
      this.loadRoles()
    },
    async hOk(row) {
      console.log(row)
      // 判断是否必填
      if (!row.editRow.name || !row.editRow.description) {
        this.$message.error('内容必填')
        return
      }
      // 调用接口
      await updateRole(row.editRow)
      this.$message.success('更新成功')
      // 退出编辑
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
      // 重发请求
      this.loadRoles()
    },
    hEdit(row) {
      // 启用编辑
      row.isEdit = true
    },
    async doAdd() {
      await addRole(this.formData)
      this.$message.success('添加成功')
      // 关闭弹框
      this.showDialog = false

      // resetFileds要生效的前提是：做表单校验
      this.$refs.roleForm.resetFields()
      // 想要看到添加的数据 跳转到最后一页
      this.total = this.total + 1
      this.page = Math.ceil(this.total / this.pagesize)
      // 更新表格数据
      this.loadRoles()
    },
    // 用户确认保存
    hSave() {
      // todos： 表单校验
      this.doAdd()
    },
    hAdd() {
      this.showDialog = true
    },
    // 用户更改了每页显示几条数据
    hSizeChange(pages) {
      console.log(pages)
      // 1. 更新每页显示的条数
      this.pagesize = pages

      // 2. 更新页码为1
      this.page = 1
      // 3. 重发请求
      this.loadRoles()
    },
    // page: 当前用户选择的页数
    hCurrentChage(page) {
      // 1. 更新页码
      this.page = page
      // 2. 重发请求
      this.loadRoles()
    },
    async loadRoles() {
      const res = await getRoles({ page: this.page, pagesize: this.pagesize })
      console.log(res)
      this.list = res.data.rows
      // 给每一行都补充一个属性： isEdit，用来标记当前行是否处于编辑状态
      this.list.forEach(it => {
        // this.$set(对象，新添加的属性名，属性值)
        // 这样补充的属性是响应式的 ===> 改了值，视图会变化
        this.$set(it, 'isEdit', false)
        // 缓存-备份
        this.$set(it, 'editRow', {
          id: it.id,
          name: it.name,
          state: it.state,
          description: it.description
        })
        // it.isEdit = true
      })

      console.log(this.list)
      this.total = res.data.total
    },
    hAssign(id) {
      this.roleId = id
      this.showDialogPerm = true
      this.$nextTick(() => {
        this.$refs.refPerm.getPermiss()
      })
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
